import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import Form from './components/Form';

import * as c from '@/services/consts';
import * as api from '@/services/productParam';
import { PageContainer } from '@ant-design/pro-components';

const List: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.ProductParam | undefined>(
    undefined,
  );

  const [productId, setProductId] = useState<string | undefined>(undefined);

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const { getProduct, getProductMenuItems } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductMenuItems: model.getProductMenuItems,
    }),
  );

  const productMenuItems = getProductMenuItems(true);

  const handleFormSubmit = async (record: API.ProductParam) => {
    let result: API.Result = await api.update({
      ...current,
      ...record,
    });

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.ProductParam>[] = [
    {
      title: '产品',
      align: 'center',
      width: 100,
      dataIndex: 'productId',
      sorter: true,
      renderText: (_, record) => {
        if (record.productId) {
          const product = getProduct(record.productId);
          if (product) {
            return product.name;
          }
        }
        return '';
      },
    },
    {
      title: '名称',
      width: 260,
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '参数名',
      width: 260,
      dataIndex: 'paramKey',
      sorter: true,
    },
    {
      title: '参数值',
      dataIndex: 'paramValue',
      sorter: true,
      renderText: (val: string) => {
        if (val.length > 255) {
          return val.substring(0, 255) + '...';
        }
        return val;
      },
    },
    {
      title: '排序',
      align: 'center',
      width: 80,
      dataIndex: 'sort',
      sorter: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => {
        let cmps = [];
        if (record.editable && hasRight('productparam_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        cardProps={{ bodyStyle: { padding: 0 } }}
        columns={columns}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              //console.log('tabKey', tabKey);
              setProductId(tabKey as string);
            },
          },
        }}
        params={{
          productId:
            productId && productId !== c.DefaultOptionAll.key
              ? parseInt(productId)
              : undefined,
        }}
        request={api.list}
      />
      <Form
        visible={formVisible}
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default List;
